package bblvolume

// "cluster.addr":["127.0.0.1:7800","127.0.0.1:7800"],
// "cluster.passphrase":"abcd",
// "workdir":"/opt/bblvolume",
// "log.level":"debug",
// "log.file":"stdout",
import (
	"encoding/json"
	"io/ioutil"
	"os"
	"path/filepath"
)

var server_conf ServerConfig

type ServerConfig struct {
	_file             string
	ClusterAddr       []string `json:"cluster.addr"`
	ClusterPassphrase string   `json:"cluster.passphrase"`
	Workdir           string   `json:"workdir"`
	LogLevel          string   `json:"log.level"`
	LogFile           string   `json:"log.file"`
	Volumes           []struct {
		UUID     string `json:"uuid"`
		Name     string `json:"name"`
		Listen   string `json:"listen"`
		TranAddr string `json:"tranaddr"`
		Export   string `json:"export"`
		Type     string `json:"type"`
	} `json:"volumes"`
}

func init_config(config string) error {
	filePath, err := filepath.Abs(config)
	if err != nil {
		return err
	}
	conf, err := read_config(filePath)
	if err != nil {
		return err
	}
	conf._file = filePath
	server_conf = conf
	return nil
}

func read_config(file string) (config ServerConfig, e error) {
	b, e := ioutil.ReadFile(file)
	if e != nil {
		return config, e
	}
	e = json.Unmarshal(b, &config)
	return
}

func write_config(config ServerConfig) error {
	b, e := json.Marshal(config)
	if e != nil {
		return e
	}
	e = ioutil.WriteFile(config._file, b, os.ModePerm)
	if e != nil {
		return e
	}
	server_conf = config
	return nil
}
